package com.ecloud.common.web.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.openfeign.FeignClientProperties;
import org.springframework.cloud.openfeign.FeignClientProperties.FeignClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * Feign配置
 *
 * @author LiuGangQiang Create in 2021/07/09
 */
@Configuration
public class AutoFeignConfiguration implements RequestInterceptor {

    /**
     * 默认配置
     *
     * @author LiuGangQiang Create in 2021/08/16
     * @return {@link FeignClientProperties}
     */
    @Bean
    @Primary
    @ConfigurationProperties("feign.client")
    public FeignClientProperties config() {
        FeignClientProperties properties = new FeignClientProperties();
        FeignClientConfiguration configuration = new FeignClientConfiguration();
        /* 默认连接超时时间 单位(毫秒) */
        configuration.setConnectTimeout(5000);
        /* 默认读取超时时间 */
        configuration.setReadTimeout(25000);
        Map<String, FeignClientConfiguration> prop = new HashMap<>();
        prop.put(properties.getDefaultConfig(), configuration);
        properties.setConfig(prop);
        return properties;
    }

    /**
     * @see feign.RequestInterceptor#apply(feign.RequestTemplate)
     */
    @Override
    public void apply(RequestTemplate template) {
        /* 设置响应头 */
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        /* 转发语言环境头部信息 */
        template.header(HttpHeaders.ACCEPT_LANGUAGE, request.getHeader(HttpHeaders.ACCEPT_LANGUAGE));
        /* 转发认证头部信息 */
    }
}